package com.wallet.crypto.trustapp.createWallets;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Scroller;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.wallet.crypto.trustapp.R;
import com.wallet.crypto.trustapp.util.KeyboardCover;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;

import static android.view.View.GONE;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;

public class IntroPagerAdapter extends PagerAdapter implements View.OnClickListener {

    private final WeakReference<WalletView> host;
    private final ViewPager mViewPager;
    private final View[] mViews;//顶部标签
    private int[] titles = new int[]{R.string.s00011, R.string.s00014, R.string.s00017, R.string.s00020};
    private int[] messages = new int[]{R.string.s00012, R.string.s00015, R.string.s00018, R.string.s00021};
    private int[] hint = new int[]{R.string.s00013, R.string.s00013, R.string.s00019, R.string.s00022};
    private View[] nexts = new View[4];//下一步
    private View[] select = new View[3];//规定选择
    private EditText[] passwords = new EditText[2];//密码输入框
    private TextWatcher[] watchers = new TextWatcher[2];//TextWatcher
    private int passwordIndex;
    private TextWatcher mWatcher;
    private int nextPosition;
    private EditText ed_cw_name;
    private TextView messageP;

    IntroPagerAdapter(WalletView host, ViewPager viewPager, View[] views) {
        this.host = new WeakReference<>(host);
        mViewPager = viewPager;
        mViews = views;
    }

    @NonNull
    @SuppressLint("CutPasteId")
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View view = LayoutInflater.from(container.getContext())
                .inflate(R.layout.create_wallet_content, container, false);

        FrameLayout frameLayout = view.findViewById(R.id.fl_n);
        ((TextView) view.findViewById(R.id.tv_cw_title)).setText(titles[position]);
        TextView message = view.findViewById(R.id.tv_cw_message);
        if (position == 2)
            this.messageP = message;
        message.setText(messages[position]);
        ed_cw_name = view.findViewById(R.id.ed_cw_name);
        ed_cw_name.setHint(hint[position]);
        EditText ed_cw_password = view.findViewById(R.id.ed_cw_password);
        Button next = view.findViewById(R.id.b_cw_next);
        View back = view.findViewById(R.id.iv_cw_back);
        FrameLayout personal_information = view.findViewById(R.id.fl_personal_information);
        FrameLayout explain = view.findViewById(R.id.fl_explain);

        container.addView(view);

        if (position == 3) {//条约
            nexts[position] = view.findViewById(R.id.b_cw_next_explain);
            nexts[position].setOnClickListener(v -> nextFinish());
            select[0] = view.findViewById(R.id.cb_cw_select1);
            select[1] = view.findViewById(R.id.cb_cw_select2);
            select[2] = view.findViewById(R.id.cb_cw_select3);
        } else
            nexts[position] = next;
        nexts[position].setAlpha(0.8f);
        nexts[position].setEnabled(false);

        if (position == 0)
            back.setOnClickListener(v -> host.get().showBeginHome());
        else
            back.setOnClickListener(v -> {//返回
                if (position >= 0)
                    mViewPager.setCurrentItem(position - 1);
            });

        if (position != 3)
            KeyboardCover.autoScrollView(frameLayout, next);

        if (position == 0) {//输入昵称
            if (ed_cw_name.getVisibility() == INVISIBLE)
                ed_cw_name.setVisibility(VISIBLE);
            if (ed_cw_password.getVisibility() == VISIBLE)
                ed_cw_password.setVisibility(INVISIBLE);
            KeyboardUtils.showSoftInput(ed_cw_name);

            mWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    View next = nexts[position];
                    if (count >= 1) {
                        if (next.getAlpha() == 0.8f)
                            next.setAlpha(1.0f);
                        next.setEnabled(true);
                    } else {
                        if (next.getAlpha() == 1.0f)
                            next.setAlpha(0.8f);
                        next.setEnabled(false);
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {
                }
            };
            ed_cw_name.addTextChangedListener(mWatcher);

        } else if (position > 0 && position < 3) {//输入密码

            if (ed_cw_name.getVisibility() == VISIBLE)
                ed_cw_name.setVisibility(INVISIBLE);
            if (ed_cw_password.getVisibility() == INVISIBLE)
                ed_cw_password.setVisibility(VISIBLE);
            passwords[passwordIndex++] = ed_cw_password;

        } else if (position == 3) {//条约

            personal_information.setVisibility(GONE);
            explain.setVisibility(VISIBLE);
        }

        next.setOnClickListener(v -> nextClick(next, position));//下一步
        return view;
    }

    @Override
    public void onClick(View v) {//条约选择点击
        View nextExplain = nexts[nextPosition];//当前页的 next button
        View select1 = select[0];
        View select2 = select[1];
        View select3 = select[2];
        if (v == select1) {//选择条约1
            if (select1.isSelected())
                select1.setSelected(false);
            else
                select1.setSelected(true);
        } else if (v == select2) {//选择条约2
            if (select2.isSelected())
                select2.setSelected(false);
            else
                select2.setSelected(true);
        } else if (v == select3) {//选择条约3
            if (select3.isSelected())
                select3.setSelected(false);
            else
                select3.setSelected(true);
        }

        if (select1.isSelected() && select2.isSelected() && select3.isSelected()) {
            nextExplain.setAlpha(1.0f);
            nextExplain.setEnabled(true);
        } else {
            nextExplain.setAlpha(0.8f);
            nextExplain.setEnabled(false);
        }
    }

    //下一步
    private void nextClick(Button next, int position) {
        KeyboardCover.scrollToPosition = 0;
        KeyboardUtils.hideSoftInput(next);

        try {
            Field mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            FixedSpeedScroller myScroller = new FixedSpeedScroller(mViewPager.getContext(), new AccelerateInterpolator());
            mScroller.set(mViewPager, myScroller);
            mScroller.setAccessible(false);
        } catch (Exception ignored) {
        }

        if (position == 0) {//输入密码

            mViewPager.setCurrentItem(1);
            mViews[1].setPressed(true);

            TextWatcher watcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    View next = nexts[1];
                    nextChanged(next, start, count);
                }

                @Override
                public void afterTextChanged(Editable s) {
                }
            };
            passwords[0].addTextChangedListener(watcher);
            watchers[0] = watcher;

            KeyboardUtils.showSoftInput(passwords[0]);

        } else if (position == 1) {//再次输入密码

            mViewPager.setCurrentItem(2);
            mViews[2].setPressed(true);

            TextWatcher watcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    View next = nexts[2];
                    nextChanged(next, start, count);
                    if (start == 5 && count != 0 &&
                            !passwords[0].getText().toString().equals(s.toString())) {
                        messageP.setText(R.string.s00020);
                        messageP.setTextColor(host.get().getResources().getColor(R.color.red));
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {
                }
            };
            passwords[1].addTextChangedListener(watcher);
            watchers[1] = watcher;

            KeyboardUtils.showSoftInput(passwords[1]);

        } else if (position == 2) {//规约
            nextPosition = position + 1;

            for (View mView : mViews)
                mView.setVisibility(GONE);

            mViewPager.setCurrentItem(nextPosition);

            select[0].setOnClickListener(this);
            select[1].setOnClickListener(this);
            select[2].setOnClickListener(this);
        }
    }

    //改变下一步
    private void nextChanged(View next, int start, int count) {
        if (start == 5 && count == 0) {//密码输满，点删除
            next.setAlpha(0.8f);
            next.setEnabled(false);
        } else if (start == 5) {
            if (next.getAlpha() == 0.8f)
                next.setAlpha(1.0f);
            next.setEnabled(true);
        } else {
            if (next.getAlpha() == 1.0f)
                next.setAlpha(0.8f);
            next.setEnabled(false);
        }
    }

    //创建钱包完成，注销所有监听
    private void nextFinish() {
        KeyboardCover.removeGlobalLayoutListener();
        for (int j = 0; j < watchers.length; j++)
            passwords[j].removeTextChangedListener(watchers[j]);
        ed_cw_name.removeTextChangedListener(mWatcher);

        WalletView walletView = host.get();
        if (walletView.onNewWalletClickListener != null) {
            String s = passwords[1].getText().toString();
            walletView.onNewWalletClickListener.onNewWallet(s);
        }
    }

    @Override
    public int getCount() {
        return titles.length;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }

    public static class FixedSpeedScroller extends Scroller {
        private int mDuration = 400;

        FixedSpeedScroller(Context context, Interpolator interpolator) {
            super(context, interpolator);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, mDuration);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy) {
            super.startScroll(startX, startY, dx, dy, mDuration);
        }
    }
}